package com.party.jackclientandroid.ui_order;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.party.jackclientandroid.R;
import com.party.jackclientandroid.Constant;
import com.party.jackclientandroid.api.CouponService;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.UserService;
import com.party.jackclientandroid.BaseActivityTitle;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.CommonResult;
import com.party.jackclientandroid.bean.GoodDetail;
import com.party.jackclientandroid.controller.PayController;
import com.party.jackclientandroid.event.PayResultEvent;
import com.party.jackclientandroid.utils.PhoneUtil;

import org.greenrobot.eventbus.Subscribe;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 订单-提交订单
 */
public class SubmitOrderActivity extends BaseActivityTitle {
    @BindView(R.id.submit_order_btn)
    Button orderBtn;
    @BindView(R.id.num_tv)
    TextView numTv;
    @BindView(R.id.sum_price_tv)
    TextView sumPriceTv;
    @BindView(R.id.price_tv)
    TextView priceTv;
    @BindView(R.id.real_sum_price_tv)
    TextView realSumPriceTv;
    @BindView(R.id.phone_tv)
    TextView phoneTv;
    @BindView(R.id.whole_layout)
    RelativeLayout whole_layout;
    @BindView(R.id.goods_name_tv)
    TextView goods_name_tv;

    private GoodDetail goodsDetail;
    private CouponService couponService;
    private String buyPrice;
    private int num = 1;//数量
    private int finalNum = 1;//支付成功后的券数量
    private String sumPrice;
    private static final String TAG = "SubmitOrderActivity";
    String orderId;
    PayController payController;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit_order);
        receivePassDataIfNeed(getIntent());
        initData();
    }

    protected void initData() {
        setMiddleText("提交订单");
        couponService = new CouponService(this);
        payController = new PayController(this, priceTv);

        buyPrice = goodsDetail.getBuyPrice();
        sumPrice = calBuyPrice(num, buyPrice);
        priceTv.setText(buyPrice + "元");
        sumPriceTv.setText("¥" + sumPrice);
        realSumPriceTv.setText("实付金额 ¥" + sumPrice);
        goods_name_tv.setText(goodsDetail.getGoodsName());
        phoneTv.setText(PhoneUtil.handlePhone(mApplication.getUser().getPhone()));
    }

    protected void receivePassDataIfNeed(Intent intent) {
        goodsDetail = (GoodDetail) intent.getSerializableExtra("goodDetail_data");
    }

    @OnClick({R.id.ll_submit_order_reduce, R.id.ll_submit_order_plus})
    public void handleClickSth(View view) {
        num = Integer.parseInt(numTv.getText().toString());
        switch (view.getId()) {
            case R.id.ll_submit_order_reduce:
                num--;
                break;
            case R.id.ll_submit_order_plus:
                num++;
                break;
        }
        if (num < 1) {
            showToast("此券至少购买1张");
            return;
        }
        if (goodsDetail.getBuyPersonLimit() == -1) {
            showToast("此券不限张数");
        } else if (num > goodsDetail.getBuyPersonLimit()) {
            showToast("此券最多只能购买" + goodsDetail.getBuyPersonLimit() + "张");
            return;
        }
        sumPrice = calBuyPrice(num, buyPrice);
        numTv.setText(num + "");
        sumPriceTv.setText("¥" + sumPrice);
        realSumPriceTv.setText("实付金额 ¥" + sumPrice);
    }

    public String calBuyPrice(int num, String buyPrice) {
        BigDecimal countBd = new BigDecimal(num + "");
        BigDecimal buyPriceBd = new BigDecimal(buyPrice);
        return countBd.multiply(buyPriceBd).setScale(2, RoundingMode.HALF_DOWN).toString();
    }

    @OnClick({R.id.submit_order_btn})
    public void submitOrderBtn(View view) {
        submitOrder();
    }

    @Subscribe
    public void onPayResultEvent(PayResultEvent event) {
        //showToast(event.getPayType() + event.getResultMsg());
        if (event.getResultType() == 1) {
            switch (goodsDetail.getGoodsType()) {
                case Constant.GOODS_TYPE_SECOND_KILL:
                case Constant.GOODS_TYPE_REPLACE_MONEY:
                    Intent intent = new Intent(this, ReplaceMoneyCouponBuySuccessActivity.class);
                    intent.putExtra("order_id", orderId);
                    startActivity(intent);
                    finish();
                    break;
                case Constant.GOODS_TYPE_SPELLING_GROUP:
                case Constant.GOODS_TYPE_GROUP_BUY:
                    Intent intent1 = new Intent(this, GroupBuyCouponBuySuccessActivity.class);
                    intent1.putExtra("order_id", orderId);
                    startActivity(intent1);
                    finish();
                    break;
            }
        }
    }


    //提交订单
    public void submitOrder() {
        payController.showPayMethod(sumPrice + "", orderId, (View v) -> {
            finalNum = num;
            Map<String, String> map = new HashMap();
            map.put("token", mApplication.getToken());
            map.put("totalPrice", sumPrice);
            map.put("finalPrice", sumPrice);
            map.put("shopId", goodsDetail.getShopId() + "");
            map.put("quantity", numTv.getText().toString());
            map.put("itemId", goodsDetail.getId() + "");
            map.put("type", goodsDetail.getGoodsType() + "");
            addDisposableIoMain(couponService.submitOrder(map), new DefaultConsumer<CommonResult>(mApplication) {
                @Override
                public void operateSuccess(BaseResult<CommonResult> result) {
                    orderId = result.getData().getId() + "";
                    payController.pay(orderId);
                    hideAlertDialog();
                }
            });
        });

        payController.setInputPassFinish(null);
    }

}
